<?php
namespace app\farm\model;

use app\BaseModel;
use function Qcloud\Cos\endWith;
use think\facade\Db;

class FinanceWater extends BaseModel
{

    //1认养 2认养退款 3土地 4土地退款 5养殖 6养殖管理 7提现 8商城 9商城退款 10认养配送 11认养配送退款
    //定义表名
    protected $name = 'lbfarm_farmer_finance_water';


    protected $append = [

        'type_text',

        'create_time_text'

    ];


    /**]
     * @author chenniang
     * @DataTime: 2022-02-09 16:40
     * @功能说明:转时间格式
     */
    public function getCreateTimeTextAttr($value,$data){

        if(!empty($data['create_time'])){

            return date('Y-m-d H:i:s',$data['create_time']);
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-09 16:33
     * @功能说明:类型描述
     */
    public function getTypeTextAttr($value,$data){

        if(isset($data['type'])){

            $text = $this->getTypeData($data['type']);

            return $text;
        }

    }

    /**
     * @author chenniang
     * @DataTime: 2022-02-09 15:52
     * @功能说明:
     */
    public function getTypeData($type){

        switch ($type){

            case 1:

                $text = '认养订单收入';

                break;
            case 2:

                $text = '认养订单退款';

                break;
            case 3:

                $text = '土地订单收入';

                break;

            case 4:

                $text = '土地订单退款';

                break;
            case 5:

                $text = '养殖';

                break;
            case 6:

                $text = '养殖订单收入';

                break;
            case 7:

                $text = '提现';

                break;
            case 8:

                $text = '商城订单收入';

                break;
            case 9:

                $text = '商城退款';

                break;
            case 10:

                $text = '认养配送订单收入';

                break;
            case 11:

                $text = '认养配送订单退款';

                break;
            case 12:

                $text = '提现拒绝';

                break;

            case 13:

                $text = '土地配送订单退款';

                break;

            case 14:

                $text = '土地配送订单收入';

                break;

            case 15://地主提现

                $text = '提现';

                break;
            case 16:

                $text = '商城订单运费';

                break;
            case 17:

                $text = '商城订单运费退款';

                break;
            default:

                $text = '';

                break;
        }

        return $text;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-15 10:41
     * @功能说明:获取用户消费信息
     */
    public function getUserCashData($user_id){

        $where[] = ['user_id','=',$user_id];

        $arr = [1,3,5,6,8,10,14,16];
        //总收入
        $total_cash = $this->where($where)->where('type','in',$arr)->sum('price');
        //退款
        $refund_cash= $this->where($where)->where('type','in',[2,4,9,11,13,17])->sum('price');

        $data = [

            'total_cash'  => round($total_cash,2),

            'refund_cash' => round($refund_cash,2),
            //余额
            'cash' => round($total_cash-$refund_cash,2),

        ];

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-28 14:08
     * @功能说明:分销用户的消费状况
     */
    public function resellerCashData($user_id){

        $where[] = ['user_id','=',$user_id];

        $arr = [1,3,8];
        //总收入
        $total_cash = $this->where($where)->where('type','in',$arr)->sum('price');
        //退款
        $refund_cash= $this->where($where)->where('type','in',[2,4,9])->sum('price');

        $data = [

//            'total_cash'  => round($total_cash,2),
//
//            'refund_cash' => round($refund_cash,2),
            //余额
            'order_price' => round($total_cash-$refund_cash,2),

        ];
        //查付款的订单笔数
        $list = [

            'land_order' => new LandOrder(),

            'claim_order'=> new ClaimOrder(),

            'shop_order' => new ShopOrder(),
        ];

        $dis[] = ['user_id','=',$user_id];

        $dis[] = ['pay_type','>',1];

        $num = 0;

        foreach ($list as $k=>$value){

            $num += $value->where($dis)->count();
        }

        $data['order_count'] = $num;

        return $data;

    }


    /**
     * @param $date
     * @功能说明:获取指定日期的余额
     * @author chenniang
     * @DataTime: 2022-01-12 15:10
     */
    public function getDayCash($farmer_id,$type=1,$date='',$start_time='',$end_time='',$cash_status=''){

        if($type==1){

            $where[] = ['farmer_id','=',$farmer_id];

        }else{

            $where[] = ['store_id','=',$farmer_id];

        }

        $where[] = ['role_type','=',$type];

        if(!empty($date)){

            $date = strtotime($date)+86399;

            $where[] = ['create_time','<',$date];

        }elseif (!empty($start_time)&&!empty($end_time)){

            $where[] = ['create_time','between',"$start_time,$end_time"];

        }

        if(!empty($cash_status)){

            $where[] = ['cash_status','=',$cash_status];

        }

        $arr = [1,3,5,6,8,10,14,16];
        //总收入
        $total_cash = $this->where($where)->where('type','in',$arr)->sum('price');
        //退款
        $refund_cash= $this->where($where)->where('type','in',[2,4,9,11,13,17])->sum('price');
        //提现
        $wallet_cash= $this->where($where)->where('type','in',[7])->sum('price');

        $wallet_refund_cash= $this->where($where)->where('type','in',[12])->sum('price');

        $wallet_cash-=$wallet_refund_cash;

        $data = [

            'total_cash'  => round($total_cash,2),

            'refund_cash' => round($refund_cash,2),

            'wallet_cash' => round($wallet_cash,2),

            'income_cash' => round($total_cash-$refund_cash,2),
            //余额
            'cash' => round($total_cash-$refund_cash-$wallet_cash,2),

        ];

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-12 16:28
     * @功能说明:获取指定日期的流水详情
     */
    //1认养 2认养退款 3土地 4土地退款 5养殖 6养殖管理 7提现 8商城 9商城退款 10 配送订单 11配送退款 12 拒绝提现 13土地配送订单退款 14土地配送订单 16商城订单运费 17 商城订单运费退款
    public function getDateList($farmer_id,$date,$type=1,$cash_status=2){

        if($type==1){

            $dis = [

                'farmer_id' => $farmer_id
            ];

            $arr = [

                1  => 'claim_cash',

                3  => 'land_cash',

                7  => 'wallet_cash',

                6  => 'breed_cash',

                16 => 'shop_send_cash',

                10 => 'claim_send_cash',

                14 => 'land_send_cash',

                11 => 'claim_send_refund_cash',

                13 => 'land_send_refund_cash',

                12 => 'wallet_refund_cash',

            ];
        }else{
            $arr = [

                7 => 'wallet_cash',

                8 => 'shop_cash',

                9 => 'shop_refund_cash',

                12 => 'wallet_refund_cash',


            ];

            $dis = [

                'store_id' => $farmer_id
            ];

        }

        $dis['role_type'] = $type;

        if(!empty($date)){

            $dis['create_date'] = $date;

        }

        if(!empty($cash_status)){

            $dis['cash_status'] = $cash_status;

        }

        foreach ($arr as $key=>$value){

            $dis['type']  = $key;

            $list[$value] = $this->where($dis)->sum('price');

        }

        if($type==1){

            $list['claim_send_cash'] -= $list['claim_send_refund_cash'];

            $list['land_send_cash']  -= $list['land_send_refund_cash'];
        }

        $list['wallet_cash'] -= $list['wallet_refund_cash'];


        return $list;
    }

    /**
     * @author chenniang
     * @DataTime: 2021-12-29 11:17
     * @功能说明:添加流水
     */
    public function addWater($order_id,$type,$role_type=1,$cash_status=0){

        $data  = $this->getModel($type);

        $order = $data['model']->dataInfo(['id'=>$order_id]);
        //查询店铺的用户id
        if($role_type==2&&!empty($order['store_id'])){

            $farmer_model = new Farmer();

            $landlord_id = $farmer_model->where(['id'=>$order['store_id']])->value('user_id');

        }else{

            $landlord_id = 0;
        }
        //商城订单需要减去运费
        if($type==8){

            $order['pay_price'] -= $order['freight'];
        }
        //商城退款需要减去运费
        if($type==9){

            $order['pay_price'] -= $order['car_price'];
        }
        //商城订单农场主获得运费
        if($type==16){

            $order['pay_price'] = $order['freight'];
        }
        //商城退款农场主退运费
        if($type==17){

            $order['pay_price'] = $order['car_price'];
        }

        $insert = [

            'uniacid'     => $order['uniacid'],

            'user_id'     => $order['user_id'],

            'role_type'   => $role_type,

            'farmer_id'   => !empty($order['farmer_id'])?$order['farmer_id']:0,

            'landlord_id' => $landlord_id,

            'store_id'    => !empty($order['store_id'])?$order['store_id']:0,

            'price'       => $order['pay_price'],

            'order_code'  => $order['order_code'],

            'cash_time'   => !empty($order['cash_time'])?$order['cash_time']:0,

            'cash_status' => $cash_status,

            'order_id'    => $order_id,

            'type'        => $type,

            'add'         => $data['add'],

            'create_time' => time(),

            'create_date' => date('Y-m-d',time()),

        ];

        $res = $this->dataAdd($insert);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-02-08 16:25
     * @功能说明:资金到账
     */
    public function cashArrival($farmer_id=0,$landlord_id=0,$id=0){

        $dis[] = ['cash_status','=',1];

        $dis[] = ['cash_time','<',time()];

        $dis[] = ['price','<>',0];

        if(!empty($farmer_id)){

            $dis[] = ['farmer_id','=',$farmer_id];

        }

        if(!empty($landlord_id)){

            $dis[] = ['landlord_id','=',$landlord_id];

        }

        if(!empty($id)){

            $dis[] = ['id','=',$id];

        }

        $list = $this->where($dis)->select()->toArray();


        if(!empty($list)){

            $farmer_model = new Farmer();

            $water_model  = new BalanceWater();

            foreach ($list as $value){

                Db::startTrans();

                $cash = $value['add']==1?$value['price']:$value['price']*-1;
                //农场主
                if($value['role_type']==1){

                    $farmer = $farmer_model->dataInfo(['id'=>$value['farmer_id']]);

                    if(!empty($farmer)){

                        $res = $farmer_model->dataUpdate(['id'=>$value['farmer_id'],'lock'=>$farmer['lock']],['cash'=>$farmer['cash']+$cash,'lock'=>$farmer['lock']+1]);
                    }

                }else{

                    //地主
                    $order_data = [

                        'uniacid' => $value['uniacid'],

                        'user_id' => $value['landlord_id'],

                        'id'      => $value['id'],

                        'pay_price'=> abs($cash),

                    ];

                    switch ($value['type']){

                        case 8://商城订单

                            $water_type = 11;

                            $add = 1;

                            break;
                        case 9://商城退款

                            $water_type = 10;

                            $add = 0;

                            break;
                        case 12://拒绝提现

                            $water_type = 12;

                            $add = 1;

                            break;
                        case 15://提现

                            $water_type = 8;

                            $add = 0;

                            break;

                    }

                    $res = $water_model->addWater($order_data,$water_type,$add);

                    if($res==0){

                        Db::rollback();

                    }
                    //给当前店铺加减金额
                    $farmer = $farmer_model->dataInfo(['id'=>$value['store_id']]);

                    if(!empty($farmer)){

                        $res = $farmer_model->dataUpdate(['id'=>$value['store_id'],'lock'=>$farmer['lock']],['cash'=>$farmer['cash']+$cash,'lock'=>$farmer['lock']+1]);
                    }

                }

                if(isset($res)&&$res==0){

                    Db::rollback();

                }


                $res = $this->dataUpdate(['id'=>$value['id'],'cash_status'=>1],['cash_status'=>2]);

                if($res==0){

                    Db::rollback();

                }

                Db::commit();

            }

        }

        return true;
    }


    /**
     * @param $user_id
     * @功能说明:地主冻结金额
     * @author chenniang
     * @DataTime: 2022-02-16 14:15
     */
    public function landordFrozenCash($user_id){

        $this->cashArrival(0,$user_id);

        $dis[] = ['landlord_id','=',$user_id];

        $dis[] = ['role_type','=',2];

        $dis[] = ['cash_status','in',[0,1]];

        $cash = $this->where($dis)->where('type','=',8)->sum('price');

        $refund_cash = $this->where($dis)->where('type','=',9)->sum('price');

        return round($cash-$refund_cash,2);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-12-29 11:29
     * @功能说明:更具type获取模型
     */
    public function getModel($type){

        switch ($type){

            case 1:

                $data['model'] = new ClaimOrder();

                $data['add']   = 1;

                break;

            case 2:

                $data['model'] = new ClaimOrder();

                $data['add']   = 0;

                break;

            case 3:

                $data['model'] = new LandOrder();

                $data['add']   = 1;

                break;

            case 6:

                $data['model'] = new BreedOrder();

                $data['add']   = 1;

                break;

            case 7:

                $data['model'] = new Wallet();

                $data['add']   = 0;

                break;

            case 8:

                $data['model'] = new ShopOrder();

                $data['add']   = 1;

                break;
            case 9:

                $data['model'] = new ShopRefund();

                $data['add']   = 0;

                break;

            case 10:
                //认养配送订单
                $data['model'] = new SendOrder();

                $data['add']   = 1;

                break;

            case 11:
                //认养订单退款
                $data['model'] = new SendOrder();

                $data['add']   = 0;

                break;
            case 12:
                //拒绝提现
                $data['model'] = new Wallet();

                $data['add']   = 1;

                break;
            case 13:
                //土地订单退款
                $data['model'] = new SendOrder();

                $data['add']   = 0;

                break;
            case 14:
                //土地配送订单
                $data['model'] = new SendOrder();

                $data['add']   = 1;

                break;

            case 15:
                //地主提现
                $data['model'] = new Wallet();

                $data['add']   = 0;

                break;
            case 16:
                //商城订单农场主获得运费
                $data['model'] = new ShopOrder();

                $data['add']   = 1;

                break;
            case 17:
                //商城订单农场主获得运费退款
                $data['model'] = new ShopRefund();

                $data['add']   = 0;

                break;
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('status desc,id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:08
     * @功能说明:开启默认
     */
    public function updateOne($id){

        $user_id = $this->where(['id'=>$id])->value('user_id');

        $res = $this->where(['user_id'=>$user_id])->where('id','<>',$id)->update(['status'=>0]);

        return $res;
    }










}